#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MAX_SIZE 1024

int main(int argc, char* argv[])
{
    if(argc != 3){
        std::cerr << "Usage: " << argv[0] << " <IP> <PORT>" << std::endl;
        return -1;
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    
    // 1. 创建 sockfd
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0){
        std::cerr << "socket failed" << std::endl;
        return -1;
    }

    // 2. 填充信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = ::inet_addr(ip.c_str());

    // 3. 链接
    if (connect(sockfd, (struct sockaddr*)&server, sizeof(server)) < 0){
        std::cerr << "Connection failed" << std::endl;
        return -1;
    }

    // 4. 循环发送和接收数据
    char buf[MAX_SIZE] = {0};
    while (true) {
        std::string input;
        std::cout << "> ";
        std::getline(std::cin, input);  // 从用户输入读取消息

        if (input.empty()) continue;    // 跳过空输入

        // 发送消息到服务器
        send(sockfd, input.c_str(), input.size(), 0);
        std::cout << "Sent: " << input << std::endl;

        // 接收服务器的回显
        int bytes_received = read(sockfd, buf, MAX_SIZE);
        if (bytes_received <= 0) {
            std::cerr << "Server disconnected or error occurred" << std::endl;
            break;
        }

        buf[bytes_received] = '\0';  // 确保字符串终止
        std::cout << "Echo from server: " << buf << std::endl;
    }

    close(sockfd);  // 关闭socket
    return 0;
}